package cn.flkj.lucia2a2.controllers;


import cn.flkj.lucia2a2.config.EnvRunner;
import lombok.extern.slf4j.Slf4j;
import org.hyperledger.fabric.sdk.exception.ChaincodeEndorsementPolicyParseException;
import org.hyperledger.fabric.sdk.exception.InvalidArgumentException;
import org.hyperledger.fabric.sdk.exception.ProposalException;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * @author : 州长在手 2020/9/10 上午11:52
 * 1. 测试数据加载
 */
@Slf4j
@RestController
@CrossOrigin
@RequestMapping(value = "/sub")
public class SubstrateController {

    private final EnvRunner envRunner;

    private final String  CHAINCODE_NAME = "fabcar010802";
    public SubstrateController(EnvRunner envRunner) {
        this.envRunner = envRunner;
    }


    /**
     * echo "========================Start  queryMember========================"
     * peer chaincode query -C myc -n Log -c '{"Args":["queryMember","10000001"]}'
     * echo "========================queryMember End========================"
     *
     * @return Object
     */
    @PostMapping("/queryAllCars")
    public Object queryAllCars() throws ProposalException, IOException, InvalidArgumentException {
        String[] args = new String[]{""};
        return envRunner.getFm().invoke(CHAINCODE_NAME, "queryAllCars", args);
    }


    //Could not find the file "/tmp/HFCStore.properties"
    @PostMapping("/changeCarOwner")
    public Object changeCarOwner(@RequestParam("owner") String owner) throws ProposalException, IOException, InvalidArgumentException {
        String[] args = new String[]{"CAR9",owner};
        return envRunner.getFm().invoke(CHAINCODE_NAME, "changeCarOwner", args);
    }

    @PostMapping("/queryBlock")
    public Object queryBlock(@RequestParam("number") long number) throws ProposalException, IOException, InvalidArgumentException {
        return envRunner.fm.queryBlockByNumber(number);
    }


    // createCar
    @PostMapping("/createCar")
    public Object createCar(@RequestParam("number") int number) throws ProposalException, IOException, InvalidArgumentException {
        String[] args = new String[]{"CAR"+number,"Holden","Barina","brown","zhangshulin"};
        return envRunner.getFm().invoke(CHAINCODE_NAME, "createCar", args);
    }

    // createCar
    @PostMapping("/queryCar")
    public Object queryCar(@RequestParam("number") int number) throws ProposalException, IOException, InvalidArgumentException {
        String[] args = new String[]{"CAR"+number};
        return envRunner.getFm().query(CHAINCODE_NAME, "queryCar", args);
    }




}



